<template>
  <div class="container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索组件 -->
        <searchModule
          :subjectDate="subjectDate"
          @searchFrom="searchFrom"
          @export_excel="handleDownload22"
        ></searchModule>

        <!-- 用户管理 -->
        <el-tabs type="card" @tab-click="handleClickTab" v-model="activeName">
          <el-tab-pane label="全部" name="first"></el-tab-pane>
          <el-tab-pane label="待审核" name="second"></el-tab-pane>
          <el-tab-pane label="已审核" name="third"></el-tab-pane>
          <el-tab-pane label="已拒绝" name="fourth"></el-tab-pane>
        </el-tabs>
        <!-- 数据记录 -->
        <el-alert
          v-if="alertText"
          :title="`数据一共 ${alertText} 条`"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>
        <!-- 下面的列表 -->
        <template>
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column fixed prop="number" label="试题编号" width="150">
            </el-table-column>
            <el-table-column label="学科" width="120">
              <template slot-scope="scope">
                {{ formattingSubject(scope.row.subjectID) }}
              </template>
            </el-table-column>
            <el-table-column label="目录" width="120">
              <template slot-scope="scope">
                {{ directorysSimpleID(scope.row.catalogID) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="questionType"
              label="题型"
              :formatter="formatterQuestionType"
              width="120"
            >
            </el-table-column>
            <el-table-column label="题干" width="200">
              <template slot-scope="scope">
                <span v-html="scope.row.question"></span>
              </template>
            </el-table-column>
            <el-table-column label="录入时间" width="180">
              <template #default="scope">
                {{ scopeDayjs(scope.row.addDate) }}
              </template>
              -->
            </el-table-column>
            <el-table-column
              prop="difficulty"
              label="难度"
              width="120"
              :formatter="formatterDifficulty"
            >
            </el-table-column>
            <el-table-column prop="creator" label="录入人" width="120">
            </el-table-column>
            <el-table-column
              prop="chkState"
              label="审核状态"
              :formatter="formatterChkState"
              width="120"
            >
            </el-table-column>
            <el-table-column prop="chkRemarks" label="审核意见" width="120">
            </el-table-column>
            <el-table-column prop="chkUser" label="审核人" width="120">
            </el-table-column>
            <el-table-column label="发布状态" width="120">
              <template #default="scope">
                {{ publishStatus(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  @click="handleClick(scope.row)"
                  type="text"
                  size="small"
                  >预览</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  :disabled="scope.row.chkState !== 0"
                  @click="checkSubject(scope.row)"
                  >审核</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  :disabled="scope.row.publishState !== 0"
                  @click="modificationRouter(scope.row.id)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="undercarriage(scope.row)"
                  >{{ scope.row.publishState ? "下架" : "上架" }}</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  :disabled="scope.row.publishState !== 0"
                  @click="removeSubject(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 分页 -->
        <div class="pagingFlex">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="from.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="from.pagesize"
            layout=" prev, pager, next,sizes,jumper"
            :total="alertText"
          >
          </el-pagination>
        </div>
      </el-card>
      <!-- 点击审核的弹窗 -->
      <questions-check
        :dialogCheck.sync="dialogCheck"
        @confirmCheck="confirmCheck"
      ></questions-check>
      <questionsPreview
        :dialogPerview.sync="dialogPerview"
        :preview="preview"
        :videoURL="videoURL"
      ></questionsPreview>
    </div>
  </div>
</template>

<script>
import questionsPreview from '../components/questions-preview.vue'
import questionsCheck from '../components/questions-check.vue'
import { parseTime } from '@/utils/index'
import searchModule from '../components/search-module.vue'
import {
  choice,
  choicePublish,
  remove,
  choiceCheck,
  detail
} from '@/api/hmmm/questions'
import { simple } from '@//api/hmmm/subjects'
import { simple as directorysSimple } from '@//api/hmmm/directorys'
export default {
  components: {
    searchModule,
    questionsCheck,
    questionsPreview
  },
  data () {
    return {
      id: '',
      dialogPerview: false, // 预览
      dialogCheck: false,
      activeName: 'first',
      alertText: 0,
      tableData: [],
      from: {
        page: 1,
        pagesize: 5
      },
      subjectDate: [],
      directorysDate: [],
      preview: {},
      activeVido:
        'https://vd3.bdstatic.com/mda-kddna19hp7kh2wy6/hd/mda-kddna19hp7kh2wy6.mp4?v_from_s=hkapp-haokan-hbe&auth_key=1669720585-0-0-bff37bee91eee962d585c858d80a6198&bcevod_channel=searchbox_feed&pd=1&cd=0&pt=3&logid=2785091106&vid=4248137138256741891&abtest=&klogid=2785091106',
      videoURL: '',
      rows: []
    }
  },
  computed: {
    publishStatus () {
      return (val) => {
        if (val.chkState === 0 || val.chkState === 2) {
          return '待发布'
        }
        if (val.chkState === 1 && val.publishState === 1) {
          return '已发布'
        }
        if (val.chkState === 1 && val.publishState === 0) {
          return '已下架'
        }
      }
    }
  },
  created () {
    this.choiceMethods() // 精选题库
    this.directorys()
    this.simplesimple()
  },
  methods: {
    // 导出
    async handleDownload22 () {
      const {
        data: { items }
      } = await choice({ page: 1, pagesize: this.alertText })
      // console.log('`````', rows)
      this.rows = items
      const headersArr = [
        '试题编号',
        '学科',
        '目录',
        '题干',
        '录入时间',
        '录入人',
        '审核意见'
      ]
      const headersRelations = {
        试题编号: 'number',
        学科: 'subject',
        目录: 'catalog',
        题干: 'answer',
        录入时间: 'chkDate',
        录入人: 'chkUser',
        审核意见: 'chkRemarks'
      }
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: headersArr, // 表格的表头
          data: this.formateDate2Array(headersRelations), // 导出的数据必须是二维数组
          filename: '员工信息表', // 导出文件的文件名
          autoWidth: true, // 单元格宽度是否自适应
          bookType: 'xlsx' // 文件的后缀名
        })
      })
    },
    formateDate2Array (headersRelations) {
      const arr1 = []
      this.rows.forEach((item) => {
        const newAee = Object.keys(headersRelations).map((key) => {
          // let value = item[headersRelations[key]]
          // if (headersRelations[key] === 'formOfEmployment') {
          //   const mewobj = Employees.hireType.find((item) => item.id === Number(value))
          //   // console.log(arr)
          //   value = mewobj ? mewobj.value : '未知'
          // }
          // if (['timeOfEntry', 'correctionTime'].includes(headersRelations[key])) {
          //   value = value ? this.formTime(value) : ''
          // }

          return item[headersRelations[key]]
        })
        arr1.push(newAee)
      })
      return arr1
    },
    // 点击 预览 弹窗事件
    async handleClick (row) {
      this.dialogPerview = true
      const { data } = await detail({ id: row.id })
      this.preview = data
      this.videoURL = row.videoURL
      if (!row.videoURL || !row.videoURL.includes('http')) {
        this.videoURL = this.activeVido
      }
    },
    // 审核弹框点击确定事件
    async confirmCheck (val) {
      val.chkState = +val.chkState
      val.id = this.id
      await choiceCheck(val)
      this.choiceMethods()
      this.dialogCheck = false
      this.$message.success('操作成功')
    },
    // 点击审核
    checkSubject (row) {
      this.dialogCheck = true
      this.id = row.id
    },
    // 用户管理
    handleClickTab (val) {
      if (val.index === '0') {
        this.from = { page: 1, pagesize: 5 }
        this.choiceMethods()
      } else {
        this.from.chkState = Number(val.index) - 1
        this.choiceMethods()
      }
    },
    searchFrom (f) {
      this.choiceMethods(f)
    },
    // 学科数组
    async simplesimple () {
      const { data } = await simple()
      this.subjectDate = data
    },
    // 目录数组
    async directorys () {
      const { data } = await directorysSimple()
      this.directorysDate = data
    },
    // 目录
    directorysSimpleID (id) {
      let newds
      this.directorysDate.forEach((item) => {
        if (item.value === id) {
          newds = item.label
        }
      })
      return newds
    },
    // 学科
    formattingSubject (id) {
      let newds
      this.subjectDate.forEach((item) => {
        if (item.value === id) {
          newds = item.label
        }
      })
      return newds
    },

    /**
     *获取精选题库列表
     */
    async choiceMethods (f) {
      const { data } = await choice(f || this.from)
      this.tableData = data.items
      this.alertText = data.counts
    },
    // 题型
    formatterQuestionType (row) {
      if (row.questionType === '1') {
        return '单选'
      } else if (row.questionType === '2') {
        return '多选'
      } else {
        return '简答'
      }
    },
    // 难度
    formatterDifficulty (row) {
      if (row.questionType === '1') {
        return '简单'
      } else if (row.questionType === '2') {
        return '一般'
      } else {
        return '困难'
      }
    },
    // 审核状态
    formatterChkState (row) {
      if (row.chkState === 0) {
        return '待审核'
      } else if (row.chkState === 1) {
        return '已审核'
      } else {
        return '已拒绝'
      }
    },
    // 发布状态
    // formatterPublishState (row) {
    //   if (row.chkState === 0) {
    //     return '待审核'
    //   } else if (row.questionType === '1') {
    //     return '通过'
    //   } else {
    //     return '拒绝'
    //   }
    // },
    // 格式化时间
    scopeDayjs (d) {
      return parseTime(d)
    },
    //
    handleSizeChange (val) {
      this.from.pagesize = val
      this.choiceMethods()
    },
    // 点击页数
    handleCurrentChange (val) {
      this.from.page = val
      this.choiceMethods()
    },
    // 上架下架
    undercarriage (data) {
      this.$confirm(
        `您确认${data.publishState ? '下架' : '上架'}这道题目吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          if (data.publishState === 1) {
            data.publishState = 0
          } else {
            data.publishState = 1
          }
          await choicePublish(data)
          this.choiceMethods() // 精选题库

          this.$message({
            type: 'success',
            message: `${data.publishState ? '上架' : '下架'}成功!`
          })
        })
        .catch(() => {})
    },
    // 点击修改
    modificationRouter (id) {
      this.$router.push({ path: '/questions/new', query: { id: id } })
    },
    // 点击删除
    removeSubject (data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(data)
          this.choiceMethods() // 精选题库
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped lang='scss'>
.pagingFlex {
  float: right;

  margin: 20px 0;
  ::v-deep .el-pagination__jump {
    margin-left: 0 !important;
  }
}
</style>
